<template>
	<view class="container">
		<uni-calendar :lunar="true" :selected="selecteds" @change="dateChange" range />
		{{ selecteds }}
		<view class="button-group">
			<button @click="markStart" type="primary">标记开始</button>
			<button @click="markEnd" type="primary">标记结束</button>
		</view>
		<view class="period-list">
			<view class="period-item" v-for="(period, index) in periods" :key="index">
				<text>第 {{ index + 1 }} 次经期</text>
				<text>开始: {{ formatDate(period.start) }}</text>
				<text>结束: {{ formatDate(period.end) }}</text>
				<text>持续: {{ period.duration }} 天</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	format,
	isSameBeforeDay
} from '@/utils/day'
import {
	ref,
	computed,
	onMounted
} from 'vue'

const selecteds = ref([])
const periods = ref([])
const selectedDate = ref(format())
const formatDate = (date) => {
	if (!date) return '未设置'
	return format(date)
}

const dateChange = (e) => {
	selectedDate.value = e.fulldate
}

const markStart = () => {
	if (selectedDate.value.length === 0) {
		uni.showToast({
			title: '请先选择日期',
			icon: 'none'
		})
		return
	}
	selecteds.value = [{
		date: selectedDate.value,
		info: '开始'
	}]
	savePeriods()
}

const markEnd = () => {
	if (!selecteds.value[0]) {
		uni.showToast({
			title: '请先标记开始日期',
			icon: 'none'
		})
		return
	}
	// 是否结束时间比开始时间早
	if (isSameBeforeDay(selectedDate.value, selecteds.value[0].date)) {
		uni.showToast({
			title: '结束日期不能早于开始日期',
			icon: 'none'
		})
		return
	}
	selecteds.value = [...selecteds.value, {
		date: selectedDate.value,
		info: '结束'
	}]
	const duration = calculateDuration(selecteds.value[0].date, selecteds.value[1].date)
	periods.value.push({
		start: selecteds.value[0].date,
		end: selecteds.value[1].date,
		duration
	})
	savePeriods()
}

const calculateDuration = (start, end) => {
	const startDate = new Date(start)
	const endDate = new Date(end)
	const diffTime = Math.abs(endDate - startDate)
	return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

const savePeriods = () => {
	uni.setStorageSync('periods', JSON.stringify(periods.value))
}

onMounted(() => {
	const storedPeriods = uni.getStorageSync('periods')
	if (storedPeriods) {
		periods.value = JSON.parse(storedPeriods)
	}
})
</script>

<style>
.button-group {
	display: flex;
	justify-content: space-around;
	margin-top: 20px;
}

.period-list {
	margin-top: 20px;
}

.period-item {
	background-color: #f0f0f0;
	padding: 10px;
	margin-bottom: 10px;
	border-radius: 5px;
}

.period-item text {
	display: block;
	margin-bottom: 5px;
}
</style>